package cn.sanshuilin.kst.system.provider.write.dao;

import cn.sanshuilin.kst.common.utils.LogPrinter;
import cn.sanshuilin.kst.common.utils.Utility;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import javax.security.auth.Subject;
import java.util.List;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2017-11-29 14:53
 * Copyright 2017  by 三水林科技有限公司
 **/
@Repository
public class SubjectReq extends AbstractJpaDao<Subject> {



    public long getSubjectsCount(String strKeyword,int isTopID) {
        long count = 0;
        try {
            Query query = this.getSubjectsQuery(" COUNT(*) ", strKeyword,isTopID);
            count = Utility.toSafeLong(query.getSingleResult());
        } catch (Exception e) {
            LogPrinter.error("getSubjectsCount" + e.getMessage());
        }

        return count;
    }

    public List<Subject> getSubjects(int nPageIndex, int nPageSize, String strKeyword,int isTopID) {
        Query query = getSubjectsQuery("c", strKeyword, isTopID);
        query.setFirstResult(nPageIndex * nPageSize);
        query.setMaxResults(nPageSize);
        return query.getResultList();
    }

    public List<Subject> getSubjectByTitle(String strTitle) {
        String hql = "FROM Subject c WHERE c.Title = :Title  ";
        Query query = entityManager.createNativeQuery(hql,Subject.class);
        query.setParameter("Title", strTitle);
        List<Subject> subjects=query.getResultList();

        return subjects;
    }

    private Query getSubjectsQuery(String strChange, String strKeyword, int isTopID) {
        String hql = "SELECT " + strChange + " FROM Subject c WHERE 1=1 ";

        if(strKeyword!=""){
            hql += "AND  c.Title LIKE :Keyword ";
        }
        if(isTopID!=-1){
            hql += "AND  c.IsTopID =:isTopID ";
        }

        hql += " ORDER BY c.PubDate DESC ";

        Query query =entityManager.createNativeQuery(hql);
        if(strKeyword!=""){
            query.setParameter("Keyword","%"+ strKeyword + "%");
        }
        if(isTopID!=-1){
            query.setParameter("isTopID", isTopID);
        }
        return query;
    }
}
